MT.require("core.FS");
var child = require("child_process");


MT.extend("core.BasicPlugin")(
	MT.plugins.FontManager = function(project){
		MT.core.BasicPlugin.call(this, project, "FontManager");
		this.fontforge = this.project.config.tools.fontforge;
	},
	{
		a_getFontInfo: function(fontRaw, cb){
			var font = fontRaw.split("'").join("");
			var path = MT.core.FS.path.resolve(this.project.path + "/src" + font);
			var cmd = this.fontforge + " -script info.pe '" + path + "'";

			child.exec(cmd, {
				cwd: process.cwd() + "/bin/ff"
			}, function(err, sout, serr){
				if(err){
					MT.error("ERROR: exec fontforge", err);
					sout = '{"Family name": "'+ font +'"}';
				}
				cb(sout);
			});
		},

		a_convertFont: function(font, cb){
			if(!font){
				if(cb){cb();}
				return;
			}
			var that = this;

			this.a_getFontInfo(font, function(info){
				if(!info){
					MT.error("failed to query font", font);
				}
				that.prepareTTF(font, JSON.parse(info), cb);
			});
		},

		a_getFont: function(name, cb){
			var that = this;
			name = name.replace(/ /g, "+").trim();

			var s = this.project.server;
			s.get("http://fonts.googleapis.com/css?family="+name, function(body, res){
				if(res.statusCode < 200 || res.statusCode >= 300){
					MT.log("failed to get css file: code", res.statusCode);
					cb(false);
					return;
				}

				var start = body.indexOf("url(");
				var stop = body.substring(start).indexOf(")");
				var url = body.substring(start + 4, start + stop);
				url = url.replace(/[',"]/g, '');


				// only ttf atm
				var ext = url.split(".").pop();
				if(ext != "ttf"){
					MT.log("not ttf font", url)
					cb(false);
					return;
				}

				var fontPath = "/" + name + "." + ext;

				s.download(url, that.project.path + "/src" + fontPath, function(){
					MT.log("DONE", that.project.path + "/src" + fontPath);
					cb();
					that.a_convertFont(fontPath);
				});
			});
		},

		/*
		 * move ttf file to fonts folder
		 *
		 */
		prepareTTF: function(font, info, cb){
			var name = info["Family name"] || info["Font name"];
			
			var dst = MT.core.FS.path.resolve(this.project.path + "/src/fonts/" + name);
			var that = this;

			var b = font.split(".");
			var ext = b.pop().toLowerCase();
			var base = b.join(".");

			var src = MT.core.FS.path.resolve(this.project.path + "/src" + font);
			var se = that.project.sourceeditor;

			// make ttf if not exist
			if(ext !== "ttf"){
				console.log("TODO convert to TTF");
				if(cb){cb();}
				return;
			}

			var target = dst + base + ".ttf";
			// do not overwrite
			MT.core.FS.exists(dst, function(yes){
				if(yes){
					// all ok continue;
					if(cb){cb();}
					return;
				}
				MT.core.FS.copy(src, target, function(err){
					if(cb){cb();}

					if(err){
						MT.error("TTF -> COPY ERROR: ",err);
						return;
					}
					MT.core.FS.rm(src, function(){
						that.convert(target);
					});
				});
			});
		},

		updateFonts: function(cb){
			var data = this.project.sourceeditor.data.contents;
			for(var i=0; i<data.length; i++){
				if(data[i].name == "fonts"){
					this.genCss(data[i].contents, cb);
				}
			}
		},

		genCss: function(list, cb){
			var style = "/*This file is automatically generated by MightyEditor - do not edit it directly*/\r\n";
			var str;
			var sep = MT.core.FS.path.sep;


			for(var i=0; i<list.length; i++){
				font = list[i];
				// file .. not scanning files
				if(!font.contents || !font.contents.length){
					continue;
				}

				fontName = font.name;
				str = "@font-face {"+
					"font-family: '" + fontName + "';src:";

				var file = "";
				for(var j=font.contents.length-1; j>-1; j--){
					file = font.contents[j];
					var ext = file.name.split(".").pop();
					var path = fontName + sep + file.name;
					switch(ext){
						case "woff":
							str += "url('"+path+"') format('woff'),";
						break;
						case "woff2":
							str += "url('"+path+"') format('woff2'),";
						break;
						case "ttf":
							str += "url('"+path+"') format('truetype'),";
						break;
						case "eot":
							str += "url('"+path+"') format('embedded-opentype'),";
						break;
						case "svg":
							str += "url('"+path+"#"+fontName+"') format('svg'),";
						break;
					}
				}

				//remove last ,
				str = str.substring(0, str.length - 1) + ";";

				str += '}'+"\r\n";

				style += str;
			}

			MT.core.FS.writeFile(this.project.path + "/src/fonts/fonts.css", style, function(){
				console.log("CSS GENERATED");cb();
			});
		},

		convert: function(font, info){
			var that = this;

			// probably could write small wrapper for it.. as it is quite usable.. queue or smth
			var jobs = 4;
			var done = function(){
				jobs--;
				if(jobs > 0){
					return;
				}

				that.project.sourceeditor.updateSourceList(function(){
					that.updateFonts(function(){
						console.log("fonts updated");
						that.project.sourceeditor.updateSourceList(function(){
							that.project.sourceeditor.a_getFiles();
						});
					});
				});
			};

			// copy paste? probably need to create a new class :P
			var b = font.split(".");
			var ext = b.pop().toLowerCase();
			var base = b.join(".");


			// don't overwrite files
			MT.core.FS.exists(base + ".woff", function(yes){
				if(!yes){
					that.ttf2woff(font, done);
				}
				else{
					done();
				}
			});

			MT.core.FS.exists(base + ".woff2", function(yes){
				if(!yes){
					that.ttf2woff2(font, done);
				}
				else{
					done();
				}
			});

			MT.core.FS.exists(base + ".svg", function(yes){
				if(!yes){
					that.ttf2svg(font, done);
				}
				else{
					done();
				}
			});

			MT.core.FS.exists(base + ".eot", function(yes){
				if(!yes){
					that.ttf2eot(font, done);
				}
				else{
					done();
				}
			});

		},

		// fontforge
		ttf2woff: function(font, cb){
			font = font.split("'").join();
			var cmd = this.fontforge + " -script convert.pe '" + font + "' woff";
			this.exec(cmd, cb);
		},

		// fontforge
		ttf2svg: function(font, cb){
			font = font.split("'").join();
			var cmd = this.fontforge + " -script convert.pe '" + font + "' svg";
			this.exec(cmd, cb);
		},

		// woff2_compress
		ttf2woff2: function(font, cb){
			font = font.split("'").join();
			var cmd = "woff2_compress '" + font + "'";
			this.exec(cmd, cb, process.cwd() + "/bin");
		},

		// ttf2eot
		ttf2eot: function(font, cb){
			font = font.split("'").join();
			var b = font.split(".");
			var ext = b.pop();
			var base = b.join(".");
			var cmd = 'ttf2eot "'+font+'" > "'+base+'.eot"';
			this.exec(cmd, cb, process.cwd() + "/bin");
		},


		exec: function(cmd, cb, path){
			path = path || process.cwd() + "/bin/ff";

			child.exec(cmd, {
				cwd: path,
				env: {
					PATH: process.env.PATH + ":" + path
				}
			}, function(err, sout, serr){
				if(err){
					MT.error("ERROR: exec ", cmd, err);
					cb();
					return;
				}
				cb(sout);
			});
		}
	}
);
